package postimpl

import (
	"context"
	"go-caipu/pkg/services/admin/model"
	"go-caipu/pkg/services/admin/post"
	"gorm.io/gorm"
	"time"
)

type Service struct {
	store store
}

func ProvideService(db *gorm.DB) (*Service, error) {
	store := ProvideStore(db)
	return &Service{
		store: &store,
	}, nil
}

func (s Service) GetPostPage(ctx context.Context, cmd post.GetPostPageCommand) (data []post.Post, num int64, err error) {

	result, num, err := s.store.GetPostPage(cmd)
	if err != nil {
		return
	}
	for _, item := range result {
		data = append(data, generateDto(item))
	}
	return
}

func (s Service) Get(ctx context.Context, cmd post.GetPostCommand) (post.Post, error) {
	result, err := s.store.Get(cmd)

	if err != nil {
		return post.Post{}, err
	}
	return generateDto(result), nil
}
func generateDto(model model.SysPost) post.Post {
	result := post.Post{
		PostId:   model.PostId,
		PostName: model.PostName,
		PostCode: model.PostCode,
		Sort:     model.Sort,
		Status:   model.Status,
		Remark:   model.Remark,
	}
	result.CreatedAt = model.CreatedAt
	return result
}

func (s Service) Insert(ctx context.Context, post post.Post) error {
	sys := model.SysPost{
		PostId:   post.PostId,
		PostName: post.PostName,
		PostCode: post.PostCode,
		Sort:     post.Sort,
		Status:   post.Status,
		Remark:   post.Remark,
	}
	sys.UpdatedAt = time.Now()
	sys.UpdatedAt = time.Now()
	return s.store.Insert(sys)
}

func (s Service) Update(ctx context.Context, post post.Post) error {
	sys := model.SysPost{
		PostId:   post.PostId,
		PostName: post.PostName,
		PostCode: post.PostCode,
		Sort:     post.Sort,
		Status:   post.Status,
		Remark:   post.Remark,
	}
	sys.UpdatedAt = time.Now()
	return s.store.Update(sys)
}

func (s Service) Remove(ctx context.Context, cmd post.RemovePostCommand) error {
	return s.store.Remove(cmd)
}
